package com.java2104.controller;

import com.java2104.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@SessionAttributes(names = {"loginUser"})//将属性的作用范围扩大到会话
public class IndexController {
    @PostMapping("/login")
    @ResponseBody
    public Map asynclogin (User user,Model model){
        Map map =new HashMap();
        if ("xiaofeng".equals(user.getUsername())&&"456789".equals(user.getPassword())){
            // session.setAttribute("loginUser",user);
            model.addAttribute("loginUser",user);
            map.put("status","success");
            map.put("msg","登录成功");
        }else{
            map.put("status","fail");
            map.put("msg","用户名或密码错误");
        }
        return map;
    }

    //写一个测试方法，响应登录页面
    //ModelAndView是模型数据和逻辑视图
    //页面跳转GetMapping
    //1.浏览器地址栏输入2.点击超链接，3.提交表单get
    @GetMapping({"/login","/login.jsp","/login.html"})
    public ModelAndView login(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("appName","中软国际");
        return mv;
    }

    //模拟登录页面的访问也写一个类似功能的方法
    //执行具体的业务则用@PostMapping
    //@PostMapping(path = "/login",params = {"username=admin","password=123456"})
    public  String login(HttpSession session, User user){
        //登录成功用户的信息保存到会话中
        session.setAttribute("loginUser",user);
        return  "redirect:home";//redirect重定向

    }


    @RequestMapping("/logout")
    public View logout(HttpSession session, RedirectAttributes ra){
        User loginUser=(User)session.getAttribute("loginUser");
        String username=loginUser.getUsername();
       // model.addAttribute("username",username);
       // model.addAttribute("password",loginUser.getPassword());
        session.invalidate();//销毁会话，其中保存的登录状态也随之消失
        ra.addAttribute("username",username);//添加一个普通属性
        ra.addFlashAttribute("passwored",loginUser.getPassword());//添加一个会话作用域属性
        return new RedirectView("/login");
    }


    @RequestMapping("/home") //@RequsetMapping(value="/home") @RequestMapping(path="/home")
    public  String toHoem(@CookieValue("JSESSIONID")String sessionId,Model model){
        model.addAttribute("sessionId",sessionId);
        return "home";
    }
    @RequestMapping("/register")
    public ModelAndView add(){
        ModelAndView mv=new ModelAndView();
      //  mv.addObject("ad","注册");
        return mv;
    }
    //只接受get方式的請求http:/locahost:8080/hello?name=12&station=China
    @RequestMapping(path = "/hello",method = RequestMethod.GET)
    //@GetMapping(path = "/hello")
    public  String hello(Model model, @RequestParam("name")@ModelAttribute("name") String n,
                         @RequestParam("station")@ModelAttribute("station")String s,
                         @RequestParam("job")@ModelAttribute("job")String  j){
      model.addAttribute("list",new String []{"Java","Android","C#"});
      //将请求的参数值一并加到响应资源的属性中
//      model.addAttribute("name",n);
//      model.addAttribute("station",s);
//      model.addAttribute("job",j);
      return "b";// /WEB-INF/jsp/b.jsp
    }
    //http://localhost:8080/hello/liudehua/China/programmer
    @RequestMapping("/hello2/{name}/{station}/{job}")
    public String b(Model model, @PathVariable("name")
            String n,@PathVariable("station") String s,@PathVariable("job") String j){
        model.addAttribute("list",new String []{"影","火","水晶"});
        //将请求的参数值一并加到响应资源的属性中
        model.addAttribute("name",n);
        model.addAttribute("station",s);
        model.addAttribute("job",j);
        return "b";
    }
    @RequestMapping("/servlet")
    public  String m1(HttpSession session, HttpServletRequest request, HttpServletResponse response){
        return null;
    }
  @RequestMapping("/curUser")
  @ResponseBody
  //@SessionAttribute("loginUser")获取会话中的登录用户对象注入参数中
    public  User returnLoginUser(@SessionAttribute("loginUser") User user){
           user.setNickName("洋yyds");
           return user;
  }
  @RequestMapping("/testError")
    public String textError(){
        String str=null;
      System.out.println(str.length());//模拟程序出现空指针异常
//        if (true)
//        throw new RuntimeException("字符串长度超出十六位");
        return null;
  }
  @RequestMapping("/not_in_work_timing")
    public String notInWorkTiming(){
        return "notInWorkTime";
    }
}
